package com.mo.modular.tv.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.mo.modular.tv.dao.ZlSiteMapper;
import com.mo.tv.model.ZlSite;
import com.mo.tv.service.IZlSiteService;

/**
 * <p>
 * 站点表 服务实现类
 * </p>
 *
 * @author zh
 * @since 2018-05-07
 */
@Service
public class ZlSiteServiceImpl extends ServiceImpl<ZlSiteMapper, ZlSite> implements IZlSiteService {

	private static Logger logger = Logger.getLogger(ZlSiteServiceImpl.class);
	
	@Autowired
	private ZlSiteMapper zlSiteMapper;
	
	@Autowired
    RedisTemplate redisTemplate;
    
    @Autowired
    StringRedisTemplate stringRedisTemplate;
	
	@Override
	public List<ZlSite> findAllZlSite(String name) {
		
		return zlSiteMapper.findAllZlSite(name);
	}
	@Override
	public void dataIsShareMobile(Long id){

		zlSiteMapper.dataIsShareMobile(id);
	}
	@Override
	public void removeZlSiteById(Long id) {
		zlSiteMapper.deleteById(id);
		
	}

	@Override
	public void addZlSite(ZlSite zlSite) {
		zlSiteMapper.insert(zlSite);
		
	}
	@Override
	public void updateStatus(Long id, Integer status) {
		zlSiteMapper.updateStatus(id, status);
	}
	@Override
	public ZlSite findZlSiteByName(String name) {
		return zlSiteMapper.findZlSiteByName(name);
	}
	@Override
	public Map<String,Object> findZlSiteIdByTvId(String tvId) {
		Map<String,Object> result=new HashMap<String, Object>();
		Long siteId=null;
		String stbPrefix=null;
		Map<String,Long> entries =(Map<String,Long>) redisTemplate.opsForHash().entries("sites");
		if(entries!=null&&entries.size()>0){
			Set<String> keySet = entries.keySet();
			for(String key:keySet){
				if(tvId.contains(key)){
					siteId=entries.get(key);
					stbPrefix=key;
				}
			}
			if(siteId==null){
				List<ZlSite> findAllZlSite = zlSiteMapper.findAllZlSite(null);
				for(ZlSite zlSite:findAllZlSite){
					if(tvId.contains(zlSite.getStbPrefix())){
						siteId=zlSite.getId();
						stbPrefix=zlSite.getStbPrefix();
						redisTemplate.opsForHash().put("sites", zlSite.getStbPrefix(), zlSite.getId());
					}
				}
				if(siteId==null){
					logger.info("**********此TVID无所属站点，tvid:"+tvId+" **********");
				}
			}
		}else{
			List<ZlSite> findAllZlSite = zlSiteMapper.findAllZlSite(null);
			Map<String,Long> map=new HashMap<String, Long>();
			for(ZlSite zlSite:findAllZlSite){
				map.put(zlSite.getStbPrefix(), zlSite.getId());
				if(tvId.contains(zlSite.getStbPrefix())){
					siteId=zlSite.getId();
					stbPrefix=zlSite.getStbPrefix();
				}
			}
			redisTemplate.opsForHash().putAll("sites", map);
		}
		result.put("siteId", siteId);
		result.put("stbPrefix", stbPrefix);
		return result;
	}
	
}
